<template>
    <view class="login-container">
        <view class="login-header">
            <image class="logo" src="/static/images/logo.png" mode="aspectFit"></image>
            <text class="title">旧衣回收小程序</text>
            <text class="subtitle">让闲置衣物焕发新生</text>
        </view>

        <view class="login-options">
            <button class="wechat-login-btn" open-type="getUserInfo" @getuserinfo="handleWechatLogin">
                <text class="iconfont icon-wechat"></text>
                微信授权登录
            </button>
            <view class="divider">
                <text class="divider-text">或</text>
            </view>
        </view>

        <view class="login-form">
            <view class="input-group">
                <text class="label">手机号码</text>
                <view class="input-wrapper">
                    <input type="number" v-model="phone" placeholder="请输入手机号码" maxlength="11" />
                </view>
            </view>

            <view class="input-group">
                <text class="label">验证码</text>
                <view class="input-wrapper code-wrapper">
                    <input type="number" v-model="code" placeholder="请输入验证码" maxlength="6" />
                    <button class="code-btn" :disabled="counting" @tap="sendCode">
                        {{ counting ? `${countdown}s后重发` : '获取验证码' }}
                    </button>
                </view>
            </view>

            <view class="agreement">
                <checkbox :checked="agreed" @tap="agreed = !agreed" color="#07c160" />
                <text class="agreement-text">
                    我已阅读并同意
                    <text class="link" @tap="openAgreement('user')">《用户协议》</text>
                    和
                    <text class="link" @tap="openAgreement('privacy')">《隐私政策》</text>
                </text>
            </view>

            <button class="login-btn" :disabled="!canLogin" @tap="login">手机号登录</button>
        </view>

        <view class="login-tips">
            <text class="tips-text">登录后即可使用完整功能</text>
        </view>
    </view>
</template>

<script>
import { wxLogin, phoneLogin, sendSmsCode } from '../../services/user.js';

export default {
    data() {
        return {
            phone: '',
            code: '',
            agreed: false,
            counting: false,
            countdown: 60,
            fromPage: ''
        }
    },
    computed: {
        canLogin() {
            return this.phone.length === 11 && this.code.length === 6 && this.agreed;
        }
    },
    onLoad(options) {
        if (options.from) {
            this.fromPage = options.from;
        }
    },
    methods: {
        handleWechatLogin(e) {
            if (!this.agreed) {
                uni.showToast({
                    title: '请先同意用户协议和隐私政策',
                    icon: 'none'
                });
                return;
            }

            const userInfo = e.detail.userInfo;

            if (!userInfo) {
                uni.showToast({
                    title: '授权失败，请重试',
                    icon: 'none'
                });
                return;
            }

            // 显示加载中
            uni.showLoading({
                title: '登录中...'
            });

            // 调用微信登录
            uni.login({
                success: (res) => {
                    if (res.code) {
                        console.log('微信登录成功，code:', res.code);

                        // 调用后端登录接口
                        wxLogin(res.code, userInfo)
                            .then(userData => {
                                this.handleLoginSuccess(userData);
                            })
                            .catch(err => {
                                uni.hideLoading();
                                uni.showToast({
                                    title: err || '登录失败，请重试',
                                    icon: 'none'
                                });
                            });
                    } else {
                        uni.hideLoading();
                        uni.showToast({
                            title: '微信登录失败',
                            icon: 'none'
                        });
                    }
                },
                fail: () => {
                    uni.hideLoading();
                    uni.showToast({
                        title: '微信登录失败',
                        icon: 'none'
                    });
                }
            });
        },

        sendCode() {
            if (!/^1\d{10}$/.test(this.phone)) {
                uni.showToast({
                    title: '请输入正确的手机号码',
                    icon: 'none'
                });
                return;
            }

            // 显示加载中
            uni.showLoading({
                title: '发送中...'
            });

            // 调用发送验证码接口
            sendSmsCode(this.phone)
                .then(() => {
                    uni.hideLoading();
                    this.counting = true;
                    this.countdown = 60;

                    const timer = setInterval(() => {
                        this.countdown--;
                        if (this.countdown <= 0) {
                            clearInterval(timer);
                            this.counting = false;
                        }
                    }, 1000);

                    uni.showToast({
                        title: '验证码已发送',
                        icon: 'success'
                    });
                })
                .catch(err => {
                    uni.hideLoading();
                    uni.showToast({
                        title: err || '发送失败，请重试',
                        icon: 'none'
                    });
                });
        },

        login() {
            if (!this.canLogin) return;

            // 显示加载中
            uni.showLoading({
                title: '登录中...'
            });

            // 调用手机号登录接口
            phoneLogin(this.phone, this.code)
                .then(userData => {
                    this.handleLoginSuccess(userData);
                })
                .catch(err => {
                    uni.hideLoading();
                    uni.showToast({
                        title: err || '登录失败，请重试',
                        icon: 'none'
                    });
                });
        },

        openAgreement(type) {
            const title = type === 'user' ? '用户协议' : '隐私政策';
            uni.showModal({
                title: title,
                content: `这是${title}的内容说明，实际项目中应该跳转到相应的协议页面。`,
                showCancel: false,
                confirmText: '我知道了'
            });
        },

        handleLoginSuccess(userData) {
            uni.hideLoading();

            // 保存用户信息
            uni.setStorageSync('userInfo', userData);

            uni.showToast({
                title: '登录成功',
                icon: 'success'
            });

            // 登录成功后的导航
            setTimeout(() => {
                if (this.fromPage === 'profile') {
                    // 如果是从个人中心页面来的，则返回到个人中心
                    uni.switchTab({
                        url: '/pages/profile/index'
                    });
                } else {
                    // 否则返回上一页
                    uni.navigateBack();
                }
            }, 1500);
        }
    }
}
</script>

<style lang="scss">
.login-container {
    padding: 60rpx 40rpx;
    min-height: 100vh;
    background-color: #f8f8f8;
    display: flex;
    flex-direction: column;
}

.login-header {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 60rpx;

    .logo {
        width: 160rpx;
        height: 160rpx;
        margin-bottom: 30rpx;
    }

    .title {
        font-size: 40rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 16rpx;
    }

    .subtitle {
        font-size: 28rpx;
        color: #666;
    }
}

.login-options {
    margin-bottom: 40rpx;

    .wechat-login-btn {
        background-color: #07c160;
        color: #fff;
        font-size: 32rpx;
        padding: 24rpx 0;
        border-radius: 45rpx;
        display: flex;
        align-items: center;
        justify-content: center;

        .iconfont {
            margin-right: 10rpx;
            font-size: 40rpx;
        }

        &::after {
            border: none;
        }
    }

    .divider {
        position: relative;
        text-align: center;
        margin: 40rpx 0 20rpx;

        &::before,
        &::after {
            content: "";
            position: absolute;
            top: 50%;
            width: 40%;
            height: 1px;
            background-color: #e5e5e5;
        }

        &::before {
            left: 0;
        }

        &::after {
            right: 0;
        }

        .divider-text {
            display: inline-block;
            padding: 0 20rpx;
            font-size: 24rpx;
            color: #999;
            background-color: #f8f8f8;
            position: relative;
            z-index: 1;
        }
    }
}

.login-form {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 40rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);

    .input-group {
        margin-bottom: 40rpx;

        .label {
            font-size: 28rpx;
            color: #333;
            margin-bottom: 16rpx;
            display: block;
        }

        .input-wrapper {
            border-bottom: 1px solid #e5e5e5;
            padding: 16rpx 0;

            input {
                font-size: 32rpx;
                color: #333;
                width: 100%;
                height: 60rpx;
            }
        }

        .code-wrapper {
            display: flex;
            justify-content: space-between;
            align-items: center;

            input {
                flex: 1;
            }

            .code-btn {
                width: 200rpx;
                font-size: 24rpx;
                padding: 0;
                background-color: transparent;
                color: #07c160;
                margin: 0 0 0 20rpx;

                &:disabled {
                    color: #999;
                }

                &::after {
                    border: none;
                }
            }
        }
    }

    .agreement {
        display: flex;
        align-items: center;
        margin-bottom: 50rpx;

        .agreement-text {
            font-size: 24rpx;
            color: #666;
            margin-left: 8rpx;

            .link {
                color: #07c160;
            }
        }
    }

    .login-btn {
        width: 100%;
        height: 90rpx;
        background-color: #07c160;
        color: #fff;
        font-size: 32rpx;
        border-radius: 45rpx;
        display: flex;
        align-items: center;
        justify-content: center;

        &:disabled {
            background-color: #9ed9b4;
        }
    }
}

.login-tips {
    margin-top: 40rpx;
    text-align: center;

    .tips-text {
        font-size: 24rpx;
        color: #999;
    }
}
</style>